package com.example.swd1.gudong.main.sport.normalsport;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.Circle;
import com.amap.api.maps2d.model.CircleOptions;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.model.PolylineOptions;
import com.example.swd1.gudong.R;
import com.example.swd1.gudong.Tool.DatabaseHelper;
import com.example.swd1.gudong.Tool.SensorEventHelper;
import com.example.swd1.gudong.constant.Constant;
import com.example.swd1.gudong.main.MainActivity;
import com.example.swd1.gudong.view.FinishSportDialog;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

//==================================================================================================================
//   Author :  Shile Wu
//   Date  :  16-8-19
//   Role :   DoingSport Activity
//   Reference documents : xx
//==================================================================================================================
public class DoingSportActivity extends Activity implements View.OnClickListener, ServiceConnection,
        DoingSportService.CallBack, AdapterView.OnItemClickListener, LocationSource,
        AMapLocationListener {
    private TextView distance, hours, speedAvg, recordTypeText;
    private ImageButton continueBtn, pauseBtn, finishBtn;
    private ImageView settingImg;
    private CheckBox checkBoxVoice, checkBoxScreen, checkBoxAutoLock, checkBoxDarkMode, checkBoxAutoPause, checkBoxScreenLock;
    private ImageView imageVoice, imageScreen, imageAutoLock, imageDarkMode, imageAutoPause, imageScreenLock;
    private ImageView fullScreenBtn;
    private LinearLayout digitalLayout;
    private Animation sportPauseAnimation;
    private Animation sportContinueAnimation;
//    private Location oldLocation;
    private DoingSportService.MyBinder myBinder;
    private Timer timer;
    private TimerTask timerTask;
    private long time = 0;
    private float[] results;//save distance between to oldLocation
    private float distanceFloat = 0.0f, speedAvgFloat,distanceTemp,speedTemp;//distanceFloat(km) speedAvgFloat(km/h)
    private int paceAvgInt,pace;//paceAvgInt(m/km)
    private long hoursLong;//hoursLong(ms)
    private PopupWindow popupWindow;
    private LinearLayout sportValueLayout;
    private GridView gridView;
    private SportRecordGridViewAdapter adapter;
    private int recordTypePosition = 5;//init record type is speedAvg
    private FinishSportDialog dialog;
    private DatabaseHelper databaseHelper;
    private SQLiteDatabase writeableDataBase;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private NotificationManager mNotificationManager;
    private Notification.Builder builder;
    private Notification notification;
    private static int NOTIFICATION_ID = 1;
    private RemoteViews contentView;
    private MediaPlayer startVoice, pauseVoice, continueVoice, relaxVoice;

    private AMap aMap;
    private MapView mapView;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private LatLng oldLatLng;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private boolean mFirstFix = false;
    private Marker mLocMarker;
    private SensorEventHelper mSensorHelper;
    private Circle mCircle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doing_sport);

        //receive the location from NormalSportFragment
        oldLatLng = getIntent().getParcelableExtra("latLng");
//        aMapLocation = getIntent().getParcelableExtra("location");
////        oldLocation = getIntent().getParcelableExtra("location");
        if (oldLatLng != null) {
//            Log.d("555log", oldLocation.getLatitude() + "," + oldLocation.getLongitude());
////            startVoice = MediaPlayer.create(this, R.raw.run_start);
////            startVoice.start();
        } else {
            Log.d("555log", "oldLatLng is null");
        }

        /*-begin-201609012-shile.wu-add-for-task2781345-*/
        //old: databaseHelper = new DatabaseHelper(this);
        databaseHelper = DatabaseHelper.getInstance(this);
        /*-begin-201609012-shile.wu-add-for-task2781345-*/
        writeableDataBase = databaseHelper.getWritableDatabase();
        sharedPreferences = getSharedPreferences("setting", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        //bind service that listen the gps' change
//        bindService(new Intent(this, DoingSportService.class), this, Context.BIND_AUTO_CREATE);
        initView(savedInstanceState);
        startTimer();
        initNotification();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d("555log", "service conn");
//        myBinder = (DoingSportService.MyBinder) service;
//        myBinder.setCallBack(this);
    }

    /*
    * when location change call onDataChange(),and calculate the distance and send to handler
    * */
    @Override
    public void onDataChange(Location newLocation, int dataType) {
//        results = new float[1];
//        Location.distanceBetween(oldLocation.getLatitude(), oldLocation.getLongitude(), newLocation.getLatitude(), newLocation.getLongitude(), results);
//
//        DecimalFormat decimalFormat = new DecimalFormat("0.00");
//        distanceTemp = results[0]/1000;
//        distanceFloat = distanceFloat + (results[0] / 1000);
//        oldLocation.set(newLocation);//save the new location
//
//        String d = decimalFormat.format(distanceFloat);
//        Message message = new Message();
//        message.what = 2;
//        message.obj = d;
//        message.arg1 = dataType;
//        mHandler.sendMessage(message);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d("555log", "service disconn");
    }


    private void initView(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        mSensorHelper = new SensorEventHelper(this);
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }

        distance = (TextView) findViewById(R.id.tv_distiance);
        hours = (TextView) findViewById(R.id.tv_hours);
        speedAvg = (TextView) findViewById(R.id.tv_speed);
        recordTypeText = (TextView) findViewById(R.id.record_type_text);
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/din_condensed_bold.ttf");
        distance.setTypeface(typeFace);
        hours.setTypeface(typeFace);
        speedAvg.setTypeface(typeFace);

        continueBtn = (ImageButton) findViewById(R.id.sport_continue);
        pauseBtn = (ImageButton) findViewById(R.id.sport_pause);
        finishBtn = (ImageButton) findViewById(R.id.sport_finish);

        continueBtn.setOnClickListener(this);
        pauseBtn.setOnClickListener(this);
        finishBtn.setOnClickListener(this);

        sportValueLayout = (LinearLayout) findViewById(R.id.sport_value_layout);
        sportValueLayout.setOnClickListener(this);

        settingImg = (ImageView) findViewById(R.id.setting_img);
        settingImg.setOnClickListener(this);

        fullScreenBtn = (ImageView) findViewById(R.id.full_screen);
        fullScreenBtn.setOnClickListener(this);

        digitalLayout = (LinearLayout) findViewById(R.id.digital_layout);


//        sportPauseAnimation = AnimationUtils.loadAnimation(this,R.anim.sport_status_translate_pause_anim);
//        sportContinueAnimation = AnimationUtils.loadAnimation(this,R.anim.sport_status_translate_continue_anim);
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // aMap.setMyLocationType()
//        polyline = aMap.addPolyline(new PolylineOptions());
    }

    private void initNotification() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, DoingSportActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        contentView = new RemoteViews(getPackageName(), R.layout.notification_layout);

        mBuilder.setSmallIcon(R.drawable.icon)
                .setContentIntent(pendingIntent)
                .setTicker("sport")
                .setOngoing(true)
                .setContent(contentView);
        notification = mBuilder.build();

        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sport_continue:
                //change view status
                pauseBtn.setVisibility(View.VISIBLE);
                continueBtn.setVisibility(View.INVISIBLE);
                finishBtn.setVisibility(View.INVISIBLE);
                //
//                continueVoice = MediaPlayer.create(this, R.raw.sport_continue);
//                continueVoice.start();
//                myBinder.onRestart();
                aMap.setLocationSource(this);// 设置定位监听
                aMap.setMyLocationEnabled(true);
                startTimer();
                break;
            case R.id.sport_pause:

                pauseBtn.setVisibility(View.INVISIBLE);
                continueBtn.setVisibility(View.VISIBLE);
                finishBtn.setVisibility(View.VISIBLE);
                deactivate();
//                pauseVoice = MediaPlayer.create(this, R.raw.sport_pause);
//                pauseVoice.start();
//                myBinder.onPause();
                stopTimer();
                break;
            case R.id.sport_finish:
                if (distanceFloat > 0) {
                    showFinishPop();//can save the data into DB
//                    relaxVoice = MediaPlayer.create(this, R.raw.exercise_to_relax);
//                    relaxVoice.start();
                } else {
                    showFinishDialog();//no data to save into DB
                }
                break;
            case R.id.sport_value_layout:
                showSprotRecordPop();
                break;
            case R.id.setting_img:
                showSettingPop();
                break;
            case R.id.image_voice:
                checkBoxVoice.setChecked(!checkBoxVoice.isChecked());
                if (checkBoxVoice.isChecked()) {
                    imageVoice.setImageResource(R.drawable.ic_voice_on);
                    editor.putBoolean("settingVoice", true);
                } else {
                    imageVoice.setImageResource(R.drawable.ic_voice);
                    editor.putBoolean("settingVoice", false);
                }
                break;
            case R.id.image_screen:
                checkBoxScreen.setChecked(!checkBoxScreen.isChecked());
                if (checkBoxScreen.isChecked()) {
                    imageScreen.setImageResource(R.drawable.ic_screenlight_on);
                    editor.putBoolean("settingScreen", true);
                } else {
                    imageScreen.setImageResource(R.drawable.ic_screenlight);
                    editor.putBoolean("settingScreen", false);
                }
                break;
            case R.id.image_autolock:
                checkBoxAutoLock.setChecked(!checkBoxAutoLock.isChecked());
                if (checkBoxAutoLock.isChecked()) {
                    imageAutoLock.setImageResource(R.drawable.ic_autolock_on);
                    editor.putBoolean("settingAutoLock", true);
                } else {
                    imageAutoLock.setImageResource(R.drawable.ic_autolock);
                    editor.putBoolean("settingAutoLock", false);
                }
                break;
            case R.id.image_darkmode:
                checkBoxDarkMode.setChecked(!checkBoxDarkMode.isChecked());
                if (checkBoxDarkMode.isChecked()) {
                    imageDarkMode.setImageResource(R.drawable.ic_darkmode_on);
                    editor.putBoolean("settingDarkMode", true);
                } else {
                    imageDarkMode.setImageResource(R.drawable.ic_darkmode);
                    editor.putBoolean("settingDarkMode", false);
                }
                break;
            case R.id.image_autopause:
                checkBoxAutoPause.setChecked(!checkBoxAutoPause.isChecked());
                if (checkBoxAutoPause.isChecked()) {
                    imageAutoPause.setImageResource(R.drawable.ic_sport_set_pause_open);
                    editor.putBoolean("settingAutoPause", true);
                } else {
                    imageAutoPause.setImageResource(R.drawable.ic_sport_set_pause_closed);
                    editor.putBoolean("settingAutoPause", false);
                }
                break;
            case R.id.image_lockscreen:
                checkBoxScreenLock.setChecked(!checkBoxScreenLock.isChecked());
                if (checkBoxScreenLock.isChecked()) {
                    imageScreenLock.setImageResource(R.drawable.ic_lockscreen_on);
                    editor.putBoolean("settingScreenLock", true);
                } else {
                    imageScreenLock.setImageResource(R.drawable.ic_lockscreen);
                    editor.putBoolean("settingScreenLock", false);
                }
                break;
            case R.id.finish_and_save_text:
                //
                //write the data into database
                //
                ContentValues values = new ContentValues();
                //values.put(Constant.DATABASE_TABLE_FIELD_DISTANCE, distanceFloat * 1000);
                double distance = (int) (distanceFloat * 100) / 100.0;
                values.put(Constant.DATABASE_TABLE_FIELD_DISTANCE, distance);

                //values.put(Constant.DATABASE_TABLE_FIELD_TIME, System.currentTimeMillis());
                //Date cDate = new Date(System.currentTimeMillis());
                Calendar mCalendar = Calendar.getInstance();
                Date date = new Date(mCalendar.get(Calendar.YEAR),
                        mCalendar.get(Calendar.MONTH),
                        mCalendar.get(Calendar.DAY_OF_MONTH),
                        mCalendar.get(Calendar.HOUR_OF_DAY),
                        mCalendar.get(Calendar.MINUTE),
                        mCalendar.get(Calendar.SECOND));
                values.put(Constant.DATABASE_TABLE_FIELD_TIME, date.getTime());

                values.put(Constant.DATABASE_TABLE_FIELD_HOURS, hoursLong / 1000);
                values.put(Constant.DATABASE_TABLE_FIELD_AVG_SPEED, speedAvgFloat);
                values.put(Constant.DATABASE_TABLE_FIELD_AVG_PACE, paceAvgInt);
                writeableDataBase.insert(Constant.DATABASE_TABLE_NAME_SPORT_RECORD, null, values);
                popupWindow.dismiss();

                //close the notification
                mNotificationManager.cancel(NOTIFICATION_ID);
                deactivate();
                startActivity(new Intent(DoingSportActivity.this, MainActivity.class));
                finish();
                break;
            case R.id.full_screen:
                if(digitalLayout.getVisibility() == View.VISIBLE){
                    digitalLayout.setVisibility(View.GONE);
                    fullScreenBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_sport_screenback_pressed));
                }else {
                    digitalLayout.setVisibility(View.VISIBLE);
                    fullScreenBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_sport_fullscreen_pressed));
                }
                break;
        }
        editor.commit();
    }

    private void startTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    time += 1000;
                    message.obj = time;
                    hoursLong = time;
                    mHandler.sendMessage(message);
                }
            };
        }
        if (timer != null && timerTask != null) {
            timer.schedule(timerTask, 1000, 1000);
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                String hms = formatter.format(((long) msg.obj) - (8 * 60 * 60 * 1000));
                hours.setText(hms);
            } else if (msg.what == 2) {

                //----------------------------------
                //debug
                if (msg.arg1 == 1) {
                    Toast.makeText(DoingSportActivity.this, "real data", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(DoingSportActivity.this, "simulate data", Toast.LENGTH_SHORT).show();
                }
                //------------------------------------

                distance.setText((String) msg.obj);
                speedAvgFloat = (distanceFloat / (hoursLong / 1000) * 3600);
                Log.d("555log","speedAvgFloat:"+speedAvgFloat);
                paceAvgInt = (int) ((hoursLong / 1000) / distanceFloat);

                //update the data of notification
                contentView.setTextViewText(R.id.notification_distance, distance.getText().toString());
                contentView.setTextViewText(R.id.notification_hours, hours.getText().toString());

                if (recordTypePosition == 5) {//speedAvg
                    DecimalFormat decimalFormat = new DecimalFormat("0.0");
                    String s = decimalFormat.format(speedAvgFloat);
                    speedAvg.setText(s);
                    //update the data of notification
                    contentView.setTextViewText(R.id.notification_pace_or_speed_text, "平均速度");
                } else if (recordTypePosition == 3) {//paceAvg
                    String s = paceAvgInt / 60 + "'" + paceAvgInt % 60 + "\"";
                    speedAvg.setText(s);
                    //update the data of notification
                    contentView.setTextViewText(R.id.notification_pace_or_speed_text, "平均配速");
                }else if(recordTypePosition == 4){//speed
                    DecimalFormat decimalFormat = new DecimalFormat("0.0");
                    String s = decimalFormat.format(speedTemp);
                    speedAvg.setText(s);
                    contentView.setTextViewText(R.id.notification_pace_or_speed_text, "时速");
                }else if (recordTypePosition == 2) {//pace
                    String s = pace / 60 + "'" + pace % 60 + "\"";
                    speedAvg.setText(s);
                    contentView.setTextViewText(R.id.notification_pace_or_speed_text, "配速");
                }

                //update the data of notification
                contentView.setTextViewText(R.id.notification_pace_or_speed, speedAvg.getText().toString());
                mNotificationManager.notify(NOTIFICATION_ID, notification);
            }
        }
    };

    private void showSprotRecordPop() {
        backgroundAlpha(0.5f);
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popwindow_sport_value, null, false);
        gridView = (GridView) popupWindow_view.findViewById(R.id.sport_value_grid_view);
        adapter = new SportRecordGridViewAdapter(this);
        adapter.setCheckPosition(recordTypePosition);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);

        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });

    }

    private void showFinishPop() {
        backgroundAlpha(0.5f);
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popwindow_finish_sport, null, false);
        TextView finishAndSave = (TextView) popupWindow_view.findViewById(R.id.finish_and_save_text);
        finishAndSave.setOnClickListener(this);
        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    private void showFinishDialog() {
        dialog = new FinishSportDialog(this, 340, 320, R.style.dialog);
        dialog.setOnClickListener(new FinishSportDialog.OnclickListener() {
                                      @Override
                                      public void onClick(int id) {
                                          switch (id) {
                                              case R.id.finish_text:
                                                  dialog.dismiss();
                                                  //close the notification
                                                  mNotificationManager.cancel(NOTIFICATION_ID);
                                                  deactivate();
                                                  startActivity(new Intent(DoingSportActivity.this, MainActivity.class));
                                                  finish();
                                                  break;
                                              case R.id.continue_text:
                                                  dialog.dismiss();
                                                  pauseBtn.setVisibility(View.VISIBLE);
                                                  continueBtn.setVisibility(View.INVISIBLE);
                                                  finishBtn.setVisibility(View.INVISIBLE);
                                                  myBinder.onRestart();
                                                  startTimer();
                                                  break;
                                          }
                                      }
                                  }
        );
        dialog.show();
    }

    private void showSettingPop() {
        backgroundAlpha(0.5f);
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popwindow_setting, null, false);
        initSettingPopView(popupWindow_view);
        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    private void initSettingPopView(View popupWindow_view) {
        LinearLayout addShoe = (LinearLayout) popupWindow_view.findViewById(R.id.add_shoe);
        View line = popupWindow_view.findViewById(R.id.gray_horizontal_line);
        addShoe.setVisibility(View.GONE);
        line.setVisibility(View.GONE);
        checkBoxVoice = (CheckBox) popupWindow_view.findViewById(R.id.checkbox_voice);
        checkBoxScreen = (CheckBox) popupWindow_view.findViewById(R.id.checkbox_screen);
        checkBoxAutoLock = (CheckBox) popupWindow_view.findViewById(R.id.checkbox_autolock);
        checkBoxDarkMode = (CheckBox) popupWindow_view.findViewById(R.id.checkbox_darkmode);
        checkBoxAutoPause = (CheckBox) popupWindow_view.findViewById(R.id.checkbox_autopause);
        checkBoxScreenLock = (CheckBox) popupWindow_view.findViewById(R.id.checkbox_lockscreen);

        imageVoice = (ImageView) popupWindow_view.findViewById(R.id.image_voice);
        imageScreen = (ImageView) popupWindow_view.findViewById(R.id.image_screen);
        imageAutoLock = (ImageView) popupWindow_view.findViewById(R.id.image_autolock);
        imageDarkMode = (ImageView) popupWindow_view.findViewById(R.id.image_darkmode);
        imageAutoPause = (ImageView) popupWindow_view.findViewById(R.id.image_autopause);
        imageScreenLock = (ImageView) popupWindow_view.findViewById(R.id.image_lockscreen);

        imageVoice.setOnClickListener(this);
        imageScreen.setOnClickListener(this);
        imageAutoLock.setOnClickListener(this);
        imageDarkMode.setOnClickListener(this);
        imageAutoPause.setOnClickListener(this);
        imageScreenLock.setOnClickListener(this);

        if (sharedPreferences.getBoolean("settingVoice", false)) {
            imageVoice.callOnClick();
        }
        if (sharedPreferences.getBoolean("settingScreen", false)) {
            imageScreen.callOnClick();
        }
        if (sharedPreferences.getBoolean("settingAutoLock", false)) {
            imageAutoLock.callOnClick();
        }
        if (sharedPreferences.getBoolean("settingDarkMode", false)) {
            imageDarkMode.callOnClick();
        }
        if (sharedPreferences.getBoolean("settingAutoPause", false)) {
            imageAutoPause.callOnClick();
        }
        if (sharedPreferences.getBoolean("settingScreenLock", false)) {
            imageScreenLock.callOnClick();
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        adapter.setCheckPosition(position);
        recordTypePosition = position;
        adapter.notifyDataSetChanged();
        popupWindow.dismiss();
        changeShowingRecord();
    }

    private void changeShowingRecord() {
        switch (recordTypePosition) {
            case 2://pace
                speedAvg.setText("00'00\"");
                recordTypeText.setText("配速(分钟/公里)");
                break;
            case 3://paceAvg
                speedAvg.setText("00'00\"");
                recordTypeText.setText("平均配速(分钟/公里)");
                break;
            case 4://speed
                speedAvg.setText("0.0");
                recordTypeText.setText("时速(公里/小时)");
                break;
            case 5://speedAvg
                speedAvg.setText("0.0");
                recordTypeText.setText("平均时速(公里/小时)");
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (pauseBtn.getVisibility() == View.VISIBLE) {
            Toast.makeText(this, "请先点击暂停按钮，结束运动", Toast.LENGTH_SHORT).show();
            return;
        } else {
            Toast.makeText(this, "请先结束运动", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            Log.d("555log",amapLocation.getAltitude()+","+amapLocation.getLatitude());
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                handlerLocationChanged(amapLocation);
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                LatLng location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                if (!mFirstFix) {
                    mFirstFix = true;
                    addCircle(location, amapLocation.getAccuracy());//添加定位精度圆
                    addMarker(location);//添加定位图标
                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                } else {
                    mCircle.setCenter(location);
                    mCircle.setRadius(amapLocation.getAccuracy());
                    mLocMarker.setPosition(location);
                }
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }
    }

    private void handlerLocationChanged(AMapLocation amapLocation){
        LatLng newLatLng = new LatLng(amapLocation.getLatitude(),amapLocation.getLongitude());
        results = new float[1];
        results[0] = AMapUtils.calculateLineDistance(oldLatLng, newLatLng);
//        Location.distanceBetween(oldLocation.getLatitude(), oldLocation.getLongitude(), amapLocation.getLatitude(), amapLocation.getLongitude(), results);
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        distanceTemp = results[0]/1000;
        distanceFloat = distanceFloat + (results[0] / 1000);
//        oldLocation.set(amapLocation);//save the new location
//        oldLatLng = newLatLng.clone();

        String d = decimalFormat.format(distanceFloat);
        Message message = new Message();
        message.what = 2;
        message.obj = d;
        message.arg1 = 1;
        mHandler.sendMessage(message);
        drawLine(newLatLng);
        oldLatLng = newLatLng.clone();
    }

    double oldla = 0,oldlg = 0, newla = 0,newlg = 0,laOffset = 0;

    private void drawLine(LatLng newLatLng){
//        laOffset += 0.01;
//        newla += laOffset;
//        LatLng latLng = new LatLng(newLatLng.latitude,newLatLng.longitude+laOffset);
        aMap.addPolyline((new PolylineOptions()).add(
                oldLatLng, newLatLng).color(
                Color.BLUE)).setGeodesic(true);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mapView.onPause();
        deactivate();
        mFirstFix = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
//        unbindService(this);
        if (startVoice != null) {
            startVoice.release();
        }
        if (continueVoice != null) {
            continueVoice.release();
        }
        if (pauseVoice != null) {
            pauseVoice.release();
        }
        if (relaxVoice != null) {
            relaxVoice.release();
        }
    }

    private void addCircle(LatLng latlng, double radius) {
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        mCircle = aMap.addCircle(options);
    }

    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }
        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.navi_map_gps_locked);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
//        mLocMarker.setTitle(LOCATION_MARKER_FLAG);
    }
}

